import {observable, action, toJS} from 'mobx';
import {WeaTableNew, WeaForm} from 'comsMobx';
import {WeaLocaleProvider} from "ecCom";
import {message, Modal, Alert} from "antd";
import * as contractManagementApi from '../api/ContractManagementApi';
import {indexOf, isBlank, parseIntValue} from '../util/CommonUtil';
import * as Constant from '../constant/Constant';
import _ from 'lodash';
import LanguageConstant from '../constant/LanguageConstant';

const confirm = Modal.confirm;
const error = Modal.error;
const {TableStore} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;

/**
 * 模板store
 */
class SystemSettingStore {

    /**
     * 是否有操作页面的权限
     *
     * @type {boolean}
     */
    @observable authorized = true;

    /**
     * 加载状态
     */
    @observable loading = false;

    /**
     * 分页控件的store
     */
    @observable initConfigTableStore = new TableStore();

    /**
     * tab页选择值
     */
    @observable selectedTabKey = Constant.SYSTEM_SETTING_TAB_BASE_SETTING;

    /**
     * 应用基础设置表单
     *
     * @type {WeaForm}
     */
    @observable baseSystemSettingForm = new WeaForm();

    /**
     * 应用基础设置表单条件
     *
     * @type {Array}
     */
    @observable baseSystemSettingFormConditions = [];

    /**
     * pdf转换服务类型值
     *
     * @type {number}
     */
    @observable pdfConversionType = -1;

    /**
     * 同步状态
     *
     * @type {boolean}
     */
    @observable synchronizing = false;

    /**
     * 字段联动相关
     *
     * @type {{}}
     */
    @observable linkages = {};

    /**
     * 永中dcs转换服务
     *
     * @type {number}
     */
    yozoDcsType = 1;

    /**
     * WPS OfficeD服务类型
     *
     * @type {number}
     */
    wpsOfficeDType = 2;

    /**
     * WPS Linux预览服务类型
     *
     * @type {number}
     */
    wpsLinuxPreviewType = 3;

    /**
     * 获取表单基础数据
     *
     * @param params
     */
    @action
    getBaseSystemSettingForm = (params = {}) => {
        contractManagementApi.getBaseSystemSettingForm(params).then(res => {
            const {code, data} = res;
            if (code == 401) {
                this.authorized = false;
            } else if (code == 200 && data) {
                const {formConditions, otherParams, linkages} = data;
                const {pdfConversionType} = otherParams;
                this.baseSystemSettingForm = new WeaForm();
                this.baseSystemSettingForm.initFormFields(formConditions);
                this.baseSystemSettingFormConditions = formConditions;
                this.pdfConversionType = pdfConversionType;
                this.linkages = linkages;
            }
        });
    }

    /**
     * 保存表单数据
     *
     * @param params
     */
    @action
    saveBaseSystemSettingForm = (params = {}) => {
        const formDatas = this.baseSystemSettingForm.getFormParams();
        const pdfConversionType = toJS(this.pdfConversionType);
        const linkages = toJS(this.linkages);
        if (formDatas) {
            const {yozodcsAddress, maxMouldFileUploadSize, wpsOfficedAddress, wpsOfficedAppId, wpsOfficedAppSecret, wpsLinuxPreviewAddress} = formDatas;
            // 校验PDF预览服务相关
            const pdfConversionTypeLinkages = linkages.pdfConversionType;
            if (_.isObject(pdfConversionTypeLinkages) && _.isArray(pdfConversionTypeLinkages["" + pdfConversionType])) {
                const pdfConversionTypeLinkageFields = pdfConversionTypeLinkages["" + pdfConversionType];
                for (let i = 0; i < pdfConversionTypeLinkageFields.length; i++) {
                    const pdfConversionTypeLinkageField = pdfConversionTypeLinkageFields[i];
                    if (!_.isObject(pdfConversionTypeLinkageField)) {
                        continue;
                    }
                    const {fieldAttr, fieldName} = pdfConversionTypeLinkageField;
                    if (fieldAttr == "MUST_INPUT" && isBlank(formDatas[fieldName])) {
                        message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
                        return;
                    }
                }
            }
            let _maxMouldFileUploadSize = parseInt(maxMouldFileUploadSize);
            if (isNaN(_maxMouldFileUploadSize) || _maxMouldFileUploadSize < 1) {
                message.error(getLabel(LanguageConstant.MOULD_UPLOAD_FILE_MAXSIZE_MUST_GREATER_THAN_ZERO, "模板文件上传最大值不能为空并且必须大于0"));
                return;
            }
        }
        this.loading = true;
        params = {...formDatas, pdfConversionType};
        contractManagementApi.saveBaseSystemSettingForm(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 200) {
                message.success(getLabel(LanguageConstant.SAVE_SUCCESS, "保存成功"));
                this.getBaseSystemSettingForm();
            } else {
                message.error(getLabel(LanguageConstant.SAVE_FAIL, "保存成功"));
            }
        });
    }

    /**
     * 下拉选择选择框选项触发事件
     *
     * @param value
     */
    @action
    onSelectChange = (fieldname, value) => {
        if (fieldname == "pdfConversionType") {
            this.pdfConversionType = value;
        }
    }


    /**
     * 获取初始化配置列表数据
     */
    @action
    getInitConfigTableData = () => {
        this.loading = true;
        contractManagementApi.getInitConfigList().then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 401) {
                this.authorized = false;
            } else if (code == 200) {
                if (data && data.sessionkey) {
                    this.initConfigTableStore.getDatas(data.sessionkey);
                }
            }
        });
    }

    /**
     * 一键初始化
     */
    @action
    affirmInitAll = () => {
        confirm({
            title: getLabel('518566', "信息确认"),
            content: getLabel('519656', "确定要初始化吗？"),
            okText: getLabel('518568', "是"),
            cancelText: getLabel('518569', "否"),
            onOk: () => this.doInitAll(),
            onCancel() {
            },
        });
    }

    /**
     * 一键初始化
     */
    @action
    doInitAll = () => {
        this.loading = true;
        contractManagementApi.initAll().then(res => {
            this.loading = false;
            const {code, notification} = res;
            if (code == 200) {
                message.success(notification == undefined ? getLabel("518560", "操作成功") : notification);
            } else if (code == 500 && notification != undefined) {
                var notifications = notification.split(";");
                const config = {
                    width: 550,
                    title: getLabel('518566', "信息确认"),
                    content: (
                        <div>
                            {this.createErrorNotificationContent(notification)}
                        </div>
                    ),
                };
                error(config);
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
            this.getInitConfigTableData();
        });
    }

    createErrorNotificationContent = (notification) => {
        var notifications = notification.split(";");
        var items = [];
        for (let i = 0; i < notifications.length; i++) {
            items.push(<p key={i}>{notifications[i]}</p>)
        }
        return items;
    }

    /**
     * tab切换事件处理
     *
     * @param tabKey
     */
    @action
    onTabChange = (tabKey) => {
        this.selectedTabKey = tabKey;
    }

    /**
     * 同步模板类型到流程表单模板类型字段
     */
    @action
    syncWorkflowMouldTypeField = () => {
        confirm({
            title: getLabel('518566', "信息确认"),
            content: getLabel('531865', "确认要同步流程模板类型字段选项吗？"),
            okText: getLabel('518568', "是"),
            cancelText: getLabel('518569', "否"),
            onOk: () => this.doSyncWorkflowMouldTypeField(),
            onCancel() {
            },
        });
    }

    /**
     * 执行同步模板类型到流程表单模板类型字段
     */
    @action
    doSyncWorkflowMouldTypeField = () => {
        this.synchronizing = true;
        const hide = message.loading(getLabel("531866", "正在同步"), 0);
        setTimeout(() => {
            contractManagementApi.syncMouldTypeToWorkflowField().then(res => {
                this.synchronizing = false;
                hide();
                const {code} = res;
                if (code == 200) {
                    message.success(getLabel("531867", "同步成功"));
                } else {
                    message.error(getLabel("531868", "同步失败"));
                }
            });
        }, 400);
    }

}

export default SystemSettingStore;